#include <Poco/Net/TCPServer.h>
#include <Poco/Net/TCPServerConnectionFactory.h>
#include <Poco/Net/TCPServerConnection.h>
#include <Poco/Net/ServerSocket.h>
#include <Poco/Net/StreamSocket.h>
#include <Poco/SharedMemory.h>

#include <string>
#include <iostream>
#include <cassert>

using namespace Poco::Net;
using namespace Poco;

class MyTCPServerConnection : public TCPServerConnection
{
public:

	MyTCPServerConnection(const StreamSocket & socket):
		TCPServerConnection(socket)
	{
	}

	virtual void run()
	{
		char buffer[1024];
		int	ret;
		StreamSocket& sock = socket();
		std::string echo("echo from server:");

		while (true)
		{
			ret = sock.sendBytes(">>>", 3);
			ret = sock.receiveBytes(buffer, 1024);

			if (ret>0)
			{
				std::cout << std::string(buffer, ret);
				// echo
				//sock.sendBytes(echo.c_str(), echo.size());
				//sock.sendBytes(buffer, ret);
			}

			if (ret==0 || std::string(buffer) == "bye")
				break;
		}
	}
};


class MyTCPServerConnectionFactory : public TCPServerConnectionFactory
{
public:
	virtual TCPServerConnection* createConnection(const StreamSocket & socket)
	{
		std::cout << "New Connection..." << std::endl;
		return new MyTCPServerConnection(socket);
	}

};


int main(int argc, char** argv)
{
	try
	{
		TCPServerConnectionFactory::Ptr factorPtr(new MyTCPServerConnectionFactory());

		TCPServer tcpServer(factorPtr, ServerSocket(5566));

		tcpServer.start();

		std::cout << "Listening..." << std::endl;

		std::string cmd;

		while (true)
		{
			std::cin >> cmd;

			if (cmd == "bye")
			{
				tcpServer.stop();
				break;
			}
		}
	}
	catch(...)
	{
		assert(0);
	}

	

	

}